package cn.edu.zjicm.wordsnet_d.synchronize;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import cn.edu.zjicm.wordsnet_d.activity.PunchOutCalendarActivity;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.view.CalendarView;
import cn.edu.zjicm.wordsnet_d.view.CalendarView.State;

public class PunchInterface extends ServerInterface {

	private static PunchInterface mInstance;

	public static PunchInterface getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new PunchInterface(context);
		}
		return mInstance;
	}

	private PunchInterface(Context context) {
		super(context);
	}

	public void punch(Handler handler, State state) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new InnerPunchThread(handler, state).start();
		} else {
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
	}

	public class InnerPunchThread extends Thread {
		String token;
		Handler handler;
		String url;
		CalendarView.State state;

		InnerPunchThread(Handler handler, CalendarView.State state) {
			this.token = AppPreference.getToken(context);
			this.handler = handler;
			this.state = state;

			url = (state == CalendarView.State.TODAY ? INNER_PUNCH_TODAY : INNER_PUNCH_YESTERDAY);
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list);
				HttpPost post = new HttpPost(url);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					LogUtil.d(str);
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					String time = result.getString("time");
					if (success) {
						int date = Integer.parseInt(time.split("T")[0]);
						WordFactory.getInstance(context).insertPunchOutLog(date);
						Message msg = new Message();
						msg.what = UserInterface.MSG_SUCCESS;
						msg.obj = state;
						msg.arg1 = date;
						handler.sendMessage(msg);
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_UNSUCCESS));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (ConnectTimeoutException e) {
				LogUtil.d("在ConnectTimeoutException中");
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.d("在Exception中");
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	public void getPunch(Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new InnerGetPunchThread(handler).start();
		} else {
			// Toast.makeText(context, "请确认网络是否连接", Toast.LENGTH_LONG).show();
			handler.sendMessage(handler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
		MobclickAgentData.getPunch(context);
	}

	public class InnerGetPunchThread extends Thread {
		String token;
		Handler handler;

		InnerGetPunchThread(Handler handler) {
			this.token = AppPreference.getToken(context);
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			NameValuePair pair1 = new BasicNameValuePair("t", token);
			list.add(pair1);
			try {
				HttpEntity entity = new UrlEncodedFormEntity(list);
				HttpPost post = new HttpPost(INNER_GET_PUNCH);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					JSONObject result = new JSONObject(str);
					String message = result.getString("message");
					boolean success = result.getBoolean("success");
					if (success) {
						int signCount = result.getInt("signCount");
						if (signCount > 0) {
							String singData[] = result.getString("signData").split(",");
							WordFactory.getInstance(context).importTablePunchOutLog(singData);
						}
						AppPreference.setDownloadPunchData(context, true);
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
					} else {
						handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WRONG_PASSWORD));
					}
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

	public void getRealDate(Handler mHandler, int realDate) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {
			new InnerGetRealDateThread(mHandler).start();
		} else {
			mHandler.sendMessage(mHandler.obtainMessage(UserInterface.MSG_BAD_NETWORK));
		}
	}

	public class InnerGetRealDateThread extends Thread {
		String token;
		Handler handler;

		InnerGetRealDateThread(Handler handler) {
			this.handler = handler;
		}

		public void run() {
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);

			try {
				HttpPost post = new HttpPost(GET_REAL_DATE);
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					LogUtil.d(str);
					JSONObject result = new JSONObject(str);
					LogUtil.d(result.toString());
					// String message = result.getString("message");
					// boolean success = result.getBoolean("success");
					// if (success) {
					// int signCount = result.getInt("signCount");
					// if (signCount > 0) {
					// String singData[] =
					// result.getString("signData").split(",");
					// WordFactory.getInstance(context).importTablePunchOutLog(singData);
					// }
					// AppPreference.setDownloadPunchData(context, true);
					// handler.sendMessage(handler.obtainMessage(UserInterface.MSG_SUCCESS));
					// } else {
					// handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WRONG_PASSWORD));
					// }
				} else {
					handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendMessage(handler.obtainMessage(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE));
			}
		}
	};

}
